package io.gbznt.modules.buss.controller;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.util.WebUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import io.gbznt.common.utils.DocUtil;
import io.gbznt.common.utils.FileConfigReader;
import io.gbznt.common.utils.PageUtils;
import io.gbznt.common.utils.R;
import io.gbznt.common.utils.ShiroUtils;
import io.gbznt.common.validator.ValidatorUtils;
import io.gbznt.common.validator.group.AddGroup;
import io.gbznt.common.validator.group.UpdateGroup;
import io.gbznt.modules.buss.entity.BussFarmlandAreaEntity;
import io.gbznt.modules.buss.service.BussFarmlandAreaService;


/**
 * 田块区域（田基地）
 *
 * @author gbznt
 * @email http://www.gbznt.com/
 * @date 2019-04-20 15:48:34
 */
@RestController
@RequestMapping("buss/bussfarmlandarea")
public class BussFarmlandAreaController {
    @Autowired
    private BussFarmlandAreaService bussFarmlandAreaService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("buss:bussfarmlandarea:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = bussFarmlandAreaService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("buss:bussfarmlandarea:info")
    public R info(@PathVariable("id") String id){
        BussFarmlandAreaEntity bussFarmlandArea = bussFarmlandAreaService.getById(id);

        return R.ok().put("bussFarmlandArea", bussFarmlandArea);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("buss:bussfarmlandarea:save")
    public R save(@RequestBody BussFarmlandAreaEntity bussFarmlandArea){
    	ValidatorUtils.validateEntity(bussFarmlandArea,AddGroup.class);
    
   	 	bussFarmlandArea.setCreateId(ShiroUtils.getUserId()+"");
    	bussFarmlandArea.setCreateTime(new Date());
        bussFarmlandAreaService.save(bussFarmlandArea);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("buss:bussfarmlandarea:update")
    public R update(@RequestBody BussFarmlandAreaEntity bussFarmlandArea){
        ValidatorUtils.validateEntity(bussFarmlandArea,AddGroup.class);
       
        bussFarmlandArea.setUpdateId(ShiroUtils.getUserId()+"");
    	bussFarmlandArea.setUpdateTime(new Date());
        Boolean re = bussFarmlandAreaService.updateById(bussFarmlandArea);//全部更新
        
        return re?R.ok():R.oldVersion();
    }

    /**
     * 保存
     */
    @RequestMapping("/saveFileAndData")
    @RequiresPermissions("buss:bussfarmlandarea:save")
    public R saveFileAndData(BussFarmlandAreaEntity bussFarmlandArea, HttpServletRequest request) {
        MultipartFile multipartFile = null;
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            MultipartHttpServletRequest multipartRequest = WebUtils.getNativeRequest(request,
                    MultipartHttpServletRequest.class);
            multipartFile = multipartRequest.getFile("file");

            if (null == multipartFile) {// 有更改文件
                return R.error("未上传文件");
            }
        }

        String rootPath = FileConfigReader.getUploadFilePath();
        R createDirRes = DocUtil.createDir(multipartFile, rootPath);
        if ((Integer) createDirRes.get("code") != 0) {
            return createDirRes;
        }

        File insertFile = (File) createDirRes.get("insertFile");

        try {
            multipartFile.transferTo(insertFile);
        } catch (IllegalStateException e) {
            e.printStackTrace();
            return R.error("上传文件出错!!!");
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("上传文件出错");
        }

        // 获取当前用户的部门信息
        bussFarmlandArea.setCreateId(ShiroUtils.getUserId());
        bussFarmlandArea.setCreateName(ShiroUtils.getUserName());
        bussFarmlandArea.setCreateTime(new Date());
        bussFarmlandArea.setLiveImage(insertFile.getPath());

        ValidatorUtils.validateEntity(bussFarmlandArea, AddGroup.class);
        Boolean re = bussFarmlandAreaService.save(bussFarmlandArea);

        return re ? R.ok() : R.error();
    }

    /**
     * 修改
     */
    @RequestMapping("/updateFileAndData")
    @RequiresPermissions("buss:bussfarmlandarea:update")
    public R updateFileAndData(BussFarmlandAreaEntity bussFarmlandArea, HttpServletRequest request) {
        MultipartFile multipartFile = null;
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            MultipartHttpServletRequest multipartRequest = WebUtils.getNativeRequest(request,
                    MultipartHttpServletRequest.class);
            multipartFile = multipartRequest.getFile("file");

            if (null != multipartFile) {// 有更改文件
                String rootPath = FileConfigReader.getUploadFilePath();
                R createDirRes = DocUtil.createDir(multipartFile, rootPath);
                if ((Integer) createDirRes.get("code") != 0) {
                    return createDirRes;
                }

                File insertFile = (File) createDirRes.get("insertFile");
                try {
                    multipartFile.transferTo(insertFile);
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                    return R.error("上传文件出错!!!");
                } catch (IOException e) {
                    e.printStackTrace();
                    return R.error("上传文件出错");
                }
                bussFarmlandArea.setLiveImage(insertFile.getPath());
            }
        }

        ValidatorUtils.validateEntity(bussFarmlandArea, UpdateGroup.class);

        bussFarmlandArea.setUpdateId(ShiroUtils.getUserId());
        bussFarmlandArea.setUpdateName(ShiroUtils.getUserName());
        bussFarmlandArea.setUpdateTime(new Date());
        Boolean re = bussFarmlandAreaService.updateById(bussFarmlandArea);

        return re ? R.ok() : R.oldVersion();
    }


    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("buss:bussfarmlandarea:delete")
    public R delete(@RequestBody String[] ids){
        bussFarmlandAreaService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * @description 基地下拉框列表
     * @author guoqiang
     * @email rd_guoqiang@139.com
     * @date 2019-04-25
     * @params  * @param params
     * @return io.gbznt.common.utils.R
     */
    @RequestMapping("/select")
    public R select(@RequestParam Map<String, Object> params){
        List<BussFarmlandAreaEntity> farmlandAreaEntityList = bussFarmlandAreaService.list(
                new QueryWrapper<BussFarmlandAreaEntity>()
        );

        return R.ok().put("list",farmlandAreaEntityList);
    }


}
